package com.woniu.map.remote;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import com.woniu.internalcommon.response.TerminalBaseResponse;
import com.woniu.internalcommon.response.TerminalInfoResponse;
import com.woniu.internalcommon.response.TerminalResponse;
import com.woniu.map.remote.url.YingYanUrl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TerminalClient {


    @Value("${map.sxid}")
    private String amapSxid;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private YingYanUrl yingYanURL;
    /**
     * 获取终端基础信息  指定tid 则只查该终端
     * @param tid
     * @param name
     * @param page
     * @return 
     */
    public List<TerminalBaseResponse> getTerminal(String tid, String name , String page) {
        String url = yingYanURL.buildGetTerminal(amapSxid, page, name, tid);

        log.info("终端服务地址：" + url);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class);
        log.info("终端服务响应：" + responseEntity.getBody());
        List<TerminalBaseResponse> terminalBaseResponses = parseTerminalListResponse(responseEntity.getBody());
        
        
        return terminalBaseResponses;
    }

    /**
     * 创建终端基础信息
     * @param name 终端名字
     * @param desc 终端描述
     * @return
     */
    public TerminalResponse addTerminal( String name, String desc) {
        String url = yingYanURL.buildAddTerminal(amapSxid,name ,desc );

        log.info("终端服务地址：" + url);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class);

        return parseTerminalResponse(responseEntity.getBody());
    }

    //        {
//            "errcode": 10000,
//                "errmsg": "OK",
//                "data": {
//            "name": "周豪1",
//                    "tid": 1381804744,
//                    "sid": 1051214
//        }
//        }

    /**
     * 查询结果转换
     * @param body
     * @return
     */
    public TerminalResponse parseTerminalResponse(String body) {
        if (StringUtils.isEmpty( body)){
            throw new IllegalArgumentException("响应体为空");
        }
        JSONObject result = JSONObject.parseObject( body);
        log.info("终端服务响应："+result);
        if (!result.get("errcode").equals(10000)) {
            throw new IllegalArgumentException("参数错误");
        }
        JSONObject data = result.getJSONObject("data");
        if (data.isEmpty()){
            return null;
        }
        return data.to(TerminalResponse.class);
    }

    /**
     * 终端基本信息列表
     * @param body
     * @return
     */
    private List<TerminalBaseResponse> parseTerminalListResponse(String body) {
        if (StringUtils.isEmpty( body)){
            throw new IllegalArgumentException("响应体为空");
        }
        JSONObject result = JSONObject.parseObject( body);
        log.info("终端服务响应："+result);
        if (!result.get("errcode").equals(10000)) {
           throw new IllegalArgumentException("参数错误");
        }
        JSONObject data = result.getJSONObject("data");
        if (data.isEmpty()){
            return null;
        }
        JSONArray results = data.getJSONArray("results");
        List<TerminalBaseResponse> terminalResponses = results.toList(TerminalBaseResponse.class);
        terminalResponses.forEach(System.out::println);

        return results.toList(TerminalBaseResponse.class);
    }

    /**
     * 周边终端搜索
     * @param center 纬经度  纬度在前  39.90935,116.397435
     * @param radius 半径 小于15000
     * @return
     */
    public List<TerminalResponse> aroundSearch(String center, Integer radius){

        String url = yingYanURL.buildAroundSearch(amapSxid, center, radius);

        log.info("终端搜索请求："+url);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, null, String.class);
        log.info("终端搜索响应："+stringResponseEntity.getBody());

        // 解析终端搜索结果
        String body = stringResponseEntity.getBody();

        return  parseAroundSearch(body);
    }

    private List<TerminalResponse> parseAroundSearch(String body) {
        if (StringUtils.isEmpty( body)){
            throw new IllegalArgumentException("鹰眼服务响应失败");
        }
        JSONObject respon = JSONObject.parseObject( body);
        log.info("终端服务响应："+respon);
        if (!respon.get("errcode").equals(10000)) {
            throw new IllegalArgumentException("参数错误");
        }
        JSONObject data = respon.getJSONObject("data");
        JSONArray results = data.getJSONArray("results");
        if (results.isEmpty()){
            return null;
        }

        return  results.toList(TerminalInfoResponse.class)
                .stream()
                .map(TerminalResponse::new)
                .collect(Collectors.toList());
    }
}
